package com.neouton.common.util;

import com.alibaba.excel.util.StringUtils;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public  class MapRemoveNullUtil {
    /**
      * 移除map中空key或者value空值
     *
     * @param map
     */
    public static void removeNullEntry(Map map) {
               removeNullKey(map);
               removeNullValue(map);
    }

    public static void removeNullKey(Map map) {
        Set set = map.keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
            Object obj = iterator.next();
            remove(obj, iterator);
        }
    }

    public static void removeNullValue(Map map) {
        Set set = map.keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
            Object obj = iterator.next();
            Object value = map.get(obj);
            remove(value, iterator);
        }
    }

    private static void remove(Object obj, Iterator iterator) {
         if (obj instanceof String) {
             String str = (String) obj;
             if (StringUtils.isBlank(str)) {
                 iterator.remove();
             }

         } else if (obj instanceof Collection) {
             Collection col = (Collection) obj;
             if (col == null || col.isEmpty()) {
                 iterator.remove();
             }
         } else if (obj instanceof Map) {
             Map temp = (Map) obj;
             if (temp == null || temp.isEmpty()) {
                 iterator.remove();
             }
         } else if (obj instanceof Object[]) {
             Object[] array = (Object[]) obj;
             if (array == null || array.length <= 0) {
                 iterator.remove();
             }
         } else {
             if (obj == null) {
                 iterator.remove();
             }
         }
   }
}
